import React from 'react';
import FileUploadTool from 'shared/utils/upload';
import joinUrl from 'shared/utils/joinUrl';
import Toast from 'antd-mobile/lib/toast';
import InputItem from 'antd-mobile/lib/input-item';
import TextareaItem from 'antd-mobile/lib/textarea-item'
import List from 'antd-mobile/lib/list';
import Picker from 'antd-mobile/lib/picker';
import { fetchReturnReasonApi } from '../api' ;


export default class RefundForm extends React.Component {
  constructor(props){
    super(props);

    this.formData = {}
    this.state = {
      imgs:[],
      sn:[],
      checkedSn:[],
      reasonData:[],
      reasonVal:[],
      reasonId:[],
    }
  }

  componentDidMount(){
    fetchReturnReasonApi().then((res)=>{
      let return_reason_id = [];
      let reason = [];
      for (let [key, value] of Object.entries(res.data)) {
        return_reason_id.push(key);
        reason.push(value);
      }
      const reasonData = return_reason_id.map((item,i)=>({label:reason[i],value:{id:item,item:reason[i]}}));
      this.setState({reasonData});
    })
  }

  handleChange = (key, value, num) => {
    if(num){
      if(value > num ){
        Toast.fail('退货数量超出可退数量！');
        return;
      }
      this.props.formChange(key, value);
    }else{
      this.props.formChange(key, value);
    }
  }

  handleUpload = (e) => {
    const self = this;
    const data = { filename: 'file', file: e.target.files[0] };
    const path = 'jiekec/index.php?route=sale/return/uploadimage'
    Toast.info('上传中', 1000000);
    FileUploadTool.post(joinUrl(path), data,
      (res) => {
        if (res.code === 1000) {
          const { imgs } = this.state;
          imgs.push(res.data.image);
          self.props.imgIdChange(res.data.return_image_id);
          this.setState({ imgs })
          Toast.hide();
        } else {
          Toast.fail('上传失败');
        }
      },
    );
  }

  handleSnOk = (val) => {
    const { checkedSn,sn } = this.state;
    if(checkedSn.indexOf(val[0].item) === -1){
      checkedSn.push(val[0].item);
      sn.push(val[0].sn_id);
    }
    this.setState({checkedSn});
    this.props.formChange('return_sn_ids',sn.join(','));
  }

  handleReasonOk = (val) => {
    const { reasonVal,reasonId } = this.state;
    if(reasonVal.indexOf(val[0].item) === -1){
      reasonVal.push(val[0].item);
      reasonId.push(val[0].id);
    }
    this.setState({reasonVal,reasonId});
    this.props.formChange('return_reason_id',reasonId.join(','));
  }


  render() {
    const { checkedSn,reasonData,reasonVal } = this.state;
    const { data,item, returnProductMoney } = this.props;
    const groupPro = item.groupbuyproductlist;
    const groupbuy = groupPro ? [item,...groupPro] : [];
    let returnPrice = 0,returnNum = 0;
    groupbuy.forEach((p) => {
      returnPrice += Number(p.price) * Number(p.quantity);
      returnNum += Number(p.quantity)
    })
    const priceRes = groupbuy.length ? returnPrice : item.price * item.quantity;
    const numRes = groupbuy.length ? returnNum : item.quantity
    const filterSn = data.sndata && data.sndata.filter((it)=>{
      if(item.sub_item_ids.length == 0){
        return item.item_id == it.item_id
      }else{
        item.sub_item_ids.forEach((sub)=>{
          return sub == it.item_id
        })
      }
    }) || [];
    const resSnData = filterSn.map((item)=>({label:item.sns,value:{sn_id:item.sn_id,item:item.sns}}));

    return (
      <div className="refund-form">
        <List className='form-item'>
          <div className="product-sn">
            <span><span className="oo">是</span>退款原因 <sup>*</sup></span>
            <Picker
              extra=''
              data={reasonData}
              cols={1}
              onOk={this.handleReasonOk}
            >
              <List.Item arrow="horizontal" />
            </Picker>
          </div>
          <div className="checked-sn">
            {
              reasonVal.length > 0 ?
                <div>
                  {reasonVal.join('   ')}
                </div> : null
            }

          </div>
          <InputItem readOnly editable={false} className="refund-input refund-input-fee" value={`￥${returnProductMoney}`}>
            <span>退款金额<sup>*</sup></span>
            {/* <div className="refund-input-fee-desc refund-reason"><span>最多￥{(Number(Number(priceRes).toFixed(0)) + Number(Number(data.express_money).toFixed(0)))},</span><span>含发货邮费¥{data.express_money}</span></div> */}
          </InputItem>
          <InputItem
            editable={!groupPro}
            className="refund-input refund-input-fee"
            min={1}
            value={numRes}
            type='digit'
            onChange={(value) =>{ this.handleChange('quantity', value, item.quantity_can_return) }}
          >
            <span>退货数量<sup>*</sup></span>
            <span className="refund-input-fee-desc refund-num">最多{numRes}个</span>
          </InputItem>
          {
            resSnData.length ?
              <div className="product-sn">
                <span>产品机身号 <sup>*</sup></span>
                <Picker
                  extra=''
                  data={resSnData}
                  cols={1}
                  onOk={this.handleSnOk}
                  disabled={resSnData.length === checkedSn.length}
                >
                  <List.Item arrow="horizontal" />
                </Picker>
                <p>请正确选择sn-号 错误选择将导致您的商品无法退货</p>
              </div> : null
          }
          {
            checkedSn.length > 0 ?
              <div className="checked-sn">
                <div>
                  {checkedSn.join('   ')}
                </div>
              </div> : null
          }

          <TextareaItem
            rows='3'
            placeholder="限200字"
            title={<span>退款说明</span>}
            onChange={(value) =>{ this.handleChange('return_info', value) }}
          />
          <div className="am-list-item am-input-item am-list-item-middle upload-input">
            <div className="am-list-line">
              <div className="am-input-label am-input-label-5">
                <span>上传图片</span>
              </div>
              <div className="img-contaier">
                {
                  this.state.imgs.map((item,i)=>(
                    <div className="img-box" key={i}>
                      <img src={item} alt="" />
                    </div>
                  ))
                }
                {
                  this.state.imgs.length < 10 ?
                    <div className="am-input-control">
                      <div className="upload-button">
                        <span>+</span>
                        <input type="file" onChange={this.handleUpload} />
                        <p>上传凭证不超过10张</p>
                      </div>
                    </div> : null
                }
              </div>
            </div>
          </div>
        </List>
      </div>
    )
  }
}